<template>
  <view :class="['settings-container', `theme-${currentTheme}`]">
    <!-- 数据备份 -->
    <view class="section">
      <view class="section-title">数据备份</view>
      <view class="section-content">
        <view class="backup-info">
          <text class="info-label">上次备份时间</text>
          <text class="info-value">{{ lastBackupTime || '从未备份' }}</text>
        </view>
        <view class="backup-tip">
          <text class="tip-text">备份文件将保存到您的设备中，可用于跨设备数据恢复或在清理小程序存储后恢复数据。</text>
        </view>
        <view class="backup-actions">
          <button 
            class="action-btn primary"
            :disabled="loading"
            @tap="handleBackup"
          >
            备份数据
          </button>
          <button 
            class="action-btn"
            :disabled="loading"
            @tap="handleRestore"
          >
            恢复数据
          </button>
        </view>
      </view>
    </view>

    <!-- 存储信息 -->
    <view class="section">
      <view class="section-title">存储信息</view>
      <view class="section-content">
        <view class="storage-info">
          <view class="info-item">
            <text class="info-label">当前使用</text>
            <text class="info-value">{{ formatStorageSize(storageInfo.currentSize) }}</text>
          </view>
          <view class="info-item">
            <text class="info-label">存储上限</text>
            <text class="info-value">{{ formatStorageSize(storageInfo.limitSize) }}</text>
          </view>
          <view class="storage-progress">
            <view 
              class="progress-bar" 
              :style="{ width: `${calculateStoragePercentage()}%` }"
              :class="{ 'warning': calculateStoragePercentage() > 80 }"
            ></view>
          </view>
          <text class="progress-text">{{ calculateStoragePercentage() }}%</text>
        </view>
        <button 
          class="action-btn primary"
          @tap="handleUpdateStorageInfo"
        >
          刷新存储信息
        </button>
      </view>
    </view>
  </view>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue';
import { useSettingsStore } from '@/store/modules/settings';
import { useThemeStore } from '@/store/modules/theme';
import useThemeMixin from '@/mixins/themeMixin';

const settingsStore = useSettingsStore();
const themeStore = useThemeStore();

const loading = ref(false);

// 设置
const settings = computed(() => settingsStore.settings);

// 上次备份时间
const lastBackupTime = computed(() => {
  return settings.value.lastBackupTime ? new Date(settings.value.lastBackupTime).toLocaleString() : null;
});

// 存储信息
const storageInfo = computed(() => settingsStore.getStorageInfo);

// 格式化存储大小
const formatStorageSize = (size: number) => {
  if (size < 1024) {
    return size + 'KB';
  } else if (size < 1024 * 1024) {
    return (size / 1024).toFixed(2) + 'MB';
  } else {
    return (size / (1024 * 1024)).toFixed(2) + 'GB';
  }
};

// 计算存储使用百分比
const calculateStoragePercentage = () => {
  if (!storageInfo.value.limitSize) return 0;
  const percentage = (storageInfo.value.currentSize / storageInfo.value.limitSize) * 100;
  return Math.min(Math.round(percentage), 100);
};

// 刷新存储信息
const handleUpdateStorageInfo = async () => {
  try {
    await settingsStore.updateStorageInfo();
    uni.showToast({
      title: '刷新成功',
      icon: 'success'
    });
  } catch (error) {
    uni.showToast({
      title: '刷新失败',
      icon: 'error'
    });
  }
};

// 主题
const currentTheme = computed(() => themeStore.currentTheme);

// 使用主题mixin
useThemeMixin();

// 备份数据
const handleBackup = async () => {
  loading.value = true;
  try {
    await settingsStore.backupData();
    uni.showToast({
      title: '备份成功',
      icon: 'success'
    });
  } catch (error) {
    uni.showToast({
      title: '备份失败',
      icon: 'error'
    });
  } finally {
    loading.value = false;
  }
};

// 恢复数据
const handleRestore = async () => {
  uni.showModal({
    title: '确认恢复',
    content: '恢复数据将覆盖当前所有数据，是否继续？',
    success: async (res) => {
      if (res.confirm) {
        loading.value = true;
        try {
          await settingsStore.restoreData();
          uni.showToast({
            title: '恢复成功',
            icon: 'success'
          });
        } catch (error) {
          uni.showToast({
            title: '恢复失败',
            icon: 'error'
          });
        } finally {
          loading.value = false;
        }
      }
    }
  });
};

// 自动备份开关
const handleAutoBackupChange = async (e: any) => {
  try {
    await settingsStore.updateSettings({
      autoBackup: e.detail.value
    });
  } catch (error) {
    uni.showToast({
      title: '设置失败',
      icon: 'error'
    });
  }
};

// 备份提醒开关
const handleBackupReminderChange = async (e: any) => {
  try {
    await settingsStore.updateSettings({
      backupReminder: e.detail.value
    });
  } catch (error) {
    uni.showToast({
      title: '设置失败',
      icon: 'error'
    });
  }
};

// 生命周期
onMounted(async () => {
  await settingsStore.loadSettings();
});
</script>

<style lang="scss">
.settings-container {
  min-height: 100vh;
  padding: 20rpx;
  background-color: var(--background-color);

  &.theme-funeral {
    --primary-light: #F5F5F5;
  }

  .section {
    margin-bottom: 30rpx;
    background-color: #fff;
    border-radius: 12rpx;
    box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.05);
    overflow: hidden;
    
    .section-title {
      font-size: 28rpx;
      font-weight: bold;
      color: #333;
      padding: 20rpx;
      border-bottom: 1px solid #eee;
    }
    
    .section-content {
      padding: 20rpx;
    }
  }
}

.backup-info {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20rpx;
  
  .info-label {
    font-size: 28rpx;
    color: #333;
  }
  
  .info-value {
    font-size: 28rpx;
    color: #999;
  }
}

.backup-tip {
  margin-bottom: 20rpx;
  
  .tip-text {
    font-size: 28rpx;
    color: #999;
  }
}

.backup-actions {
  display: flex;
  justify-content: space-between;
  
  .action-btn {
    flex: 1;
    height: 80rpx;
    background-color: #f8f8f8;
    color: #333;
    font-size: 28rpx;
    border-radius: 40rpx;
    display: flex;
    align-items: center;
    justify-content: center;
    margin: 0 10rpx;
    border: 1px solid transparent;
    
    &.primary {
      background-color: var(--primary-color);
      color: #fff !important;
    }
    
    &:not(.primary) {
      border-color: var(--primary-color);
      color: var(--primary-color);
    }
    
    &:active {
      opacity: 0.8;
    }
    
    &[disabled] {
      opacity: 0.5;
    }
  }
}

/* 存储信息样式 */
.storage-info {
  .info-item {
    display: flex;
    justify-content: space-between;
    margin-bottom: 10rpx;
    
    .info-label {
      font-size: 28rpx;
      color: #333;
    }
    
    .info-value {
      font-size: 28rpx;
      color: #666;
    }
  }
  
  .storage-progress {
    height: 20rpx;
    background-color: #f0f0f0;
    border-radius: 10rpx;
    overflow: hidden;
    margin: 15rpx 0;
    
    .progress-bar {
      height: 100%;
      background-color: var(--primary-color);
      border-radius: 10rpx;
      transition: width 0.3s;
      
      &.warning {
        background-color: #e6a23c;
      }
    }
  }
  
  .progress-text {
    font-size: 24rpx;
    color: #999;
    text-align: right;
    display: block;
    margin-bottom: 20rpx;
  }
}

.setting-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20rpx 0;
  border-bottom: 1px solid #eee;
  
  &:last-child {
    border-bottom: none;
  }
  
  .setting-label {
    font-size: 28rpx;
    color: #333;
  }
}
</style> 